package com.easylinkin.linkappapi.penetsecuremanage.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.lobar.dto.excel.ExcelResultDetailDTO;
import com.easylinkin.linkappapi.penetsecuremanage.dto.RailLinkappWorkInfoDTO;
import com.easylinkin.linkappapi.penetsecuremanage.dto.RailLinkappWorkResponsibilityDTO;
import com.easylinkin.linkappapi.penetsecuremanage.dto.ResponsibilityTempContentEnum;
import com.easylinkin.linkappapi.penetsecuremanage.entity.RailLinkappWorkInfo;
import com.easylinkin.linkappapi.penetsecuremanage.entity.RailLinkappWorkResponsibility;
import com.easylinkin.linkappapi.penetsecuremanage.mapper.RailLinkappWorkInfoMapper;
import com.easylinkin.linkappapi.penetsecuremanage.mapper.RailLinkappWorkResponsibilityMapper;
import com.easylinkin.linkappapi.penetsecuremanage.service.IRailLinkappWorkResponsibilityService;
import com.easylinkin.linkappapi.penetsecuremanage.utils.ExcelHelper;
import com.easylinkin.linkappapi.penetsecuremanage.vo.RailLinkappWorkInfoVO;
import com.easylinkin.linkappapi.penetsecuremanage.vo.RailLinkappWorkResponsibilityVO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;

/**
 * @author lyk
 * @date 2025/6/19 下午 4:33
 */
@Service
@Slf4j
public class RailLinkappWorkResponsibilityServiceImpl extends ServiceImpl<RailLinkappWorkResponsibilityMapper, RailLinkappWorkResponsibility> implements IRailLinkappWorkResponsibilityService {

    @Autowired
    private RailLinkappWorkInfoMapper workInfoMapper;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Resource
    private CommonService commonService;
    @Override
    public void initTemplate() {
        List<ResponsibilityTempContentEnum> types = ResponsibilityTempContentEnum.getTypes("2");
        if (types.size() == 0){
            return;
        }
        Date now = new Date();
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        Map<String, List<String>> maps = new HashMap<>();
        Map<String, Integer> maps_upIndex = new HashMap<>();
        Map<String, Integer> maps_index = new HashMap<>();
        for (ResponsibilityTempContentEnum type_e:types){
            String name = type_e.getName();
            List<String> strings = maps.get(name);
            if (Objects.isNull(strings)){
                strings = new ArrayList<>();
                strings.add(type_e.getContent());
                maps_upIndex.put(name, type_e.getUpIndex());
            }else{
                strings.add(type_e.getContent());
            }
            maps.put(name,strings);
            maps_index.put(type_e.getContent(), type_e.getIndex());
        }
        for (Map.Entry<String, List<String>> entry:maps.entrySet()) {
            String key = entry.getKey();
            RailLinkappWorkInfo workInfo = new RailLinkappWorkInfo();
            String workId = UUID.randomUUID().toString().replaceAll("-","");
            workInfo.setId(workId);
            workInfo.setName(key);
            workInfo.setSortIndex(maps_upIndex.get(key)==null?1:maps_upIndex.get(key));
            workInfo.setTenantId(tenantId);
            commonService.setCreateAndModifyInfo(workInfo);
            workInfoMapper.insert(workInfo);
            List<String> value = entry.getValue();
            for (String content:value){
                RailLinkappWorkResponsibility  workResponsibility = new RailLinkappWorkResponsibility();
                String id = UUID.randomUUID().toString().replaceAll("-","");
                workResponsibility.setId(id);
                workResponsibility.setWorkId(workId);
                workResponsibility.setCreateTime(now);
                workResponsibility.setTenantId(tenantId);
                workResponsibility.setContent(content);
                workResponsibility.setSortIndex(maps_index.get(content)==null?1:maps_index.get(content));
                baseMapper.insert(workResponsibility);
            }
        }
    }

    @Override
    public List<RailLinkappWorkResponsibilityVO> getList(RailLinkappWorkResponsibilityDTO dto) {
        dto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.getList(dto);
    }

    @Override
    public boolean saveToList(RailLinkappWorkResponsibilityDTO dto) {
        try {
            String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
            /**
             * 删除
             */
            List<RailLinkappWorkResponsibilityDTO> dels = dto.getDelList();
            for (RailLinkappWorkResponsibilityDTO delDTO:dels){
                if (!StringUtils.isEmpty(delDTO.getId())){
                    baseMapper.deleteById(delDTO.getId());
                }
            }
            /**
             * 新增
             */
            Date date = new Date();
            //获取 最大索引
            int iMax = baseMapper.countIndexMaxByWorkId(dto.getWorkId(), tenantId);
            if (Objects.isNull(iMax)){
                iMax = 0;
            }
            List<RailLinkappWorkResponsibilityDTO> addls = dto.getAddList();
            for (RailLinkappWorkResponsibility addDTO:addls){
                RailLinkappWorkResponsibility responsibility  = new RailLinkappWorkResponsibility();
                String id = UUID.randomUUID().toString().replaceAll("-","");
                responsibility.setId(id);
                responsibility.setWorkId(dto.getWorkId());
                responsibility.setCreateTime(date);
                responsibility.setTenantId(tenantId);
                responsibility.setContent(addDTO.getContent());
                responsibility.setSortIndex((iMax+1));
                baseMapper.insert(responsibility);
                iMax =  responsibility.getSortIndex();
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public void edit(RailLinkappWorkResponsibilityDTO dto) {
        RailLinkappWorkResponsibility railLinkappWorkResponsibility = baseMapper.selectById(dto.getId());
        railLinkappWorkResponsibility.setContent(dto.getContent());
        baseMapper.updateById(railLinkappWorkResponsibility);
    }
    
    @Override
    public void expAll(HttpServletRequest request, HttpServletResponse response) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        Map<String, List<Map<String,Object>>> transForMap = new HashMap<>();
        List<Map<String,Object>> bookNames  = new ArrayList<>();
        //查询所有的工作职责
        RailLinkappWorkInfoDTO workInfoDTO = new RailLinkappWorkInfoDTO();
        workInfoDTO.setTenantId(tenantId);
        List<RailLinkappWorkInfoVO> list = workInfoMapper.getList(workInfoDTO);
        if (list.size() == 0){
            return;
        }
        String valueName = "workName";
        String keyId = "workId";
        for (RailLinkappWorkInfoVO workInfoVO:list){
            transForMap.put(workInfoVO.getId(),new ArrayList<Map<String,Object>>());
            Map<String, Object> workName = new HashMap<>();
            workName.put(valueName,workInfoVO.getName());
            workName.put(keyId,workInfoVO.getId());
            bookNames.add(workName);
        }
        //查询所有的职责内容
        RailLinkappWorkResponsibilityDTO workResponsibilityDTO  = new RailLinkappWorkResponsibilityDTO();
        workResponsibilityDTO.setTenantId(tenantId);
        List<RailLinkappWorkResponsibilityVO> railLinkappWorkResponsibilityVOs = baseMapper.getList(workResponsibilityDTO);
        for (RailLinkappWorkResponsibilityVO rvo:railLinkappWorkResponsibilityVOs){
            List<Map<String, Object>> maps = transForMap.get(rvo.getWorkId());
            if (!Objects.isNull(maps)){
                Map<String, Object> lmap = new HashMap<>();
                lmap.put("content",rvo.getContent());
                maps.add(lmap);
                transForMap.put(rvo.getWorkId(),maps);
            }
        }
        String[] header_cn = { "职责内容"};
        String[] header = { "content"};
        String fileName = "职位职责.xlsx";
        ExcelHelper.Multipleworkbooks(header_cn,header,request,response,fileName,transForMap,bookNames,3,valueName,keyId);
    }

    @Override
    public void importWorkResponsibilityExcel(String workId, MultipartFile file, String tenantId) {
        //  ExcelResultDTO res = new ExcelResultDTO();
        try {
            List<ExcelResultDetailDTO> excelResultDetailDTOS = new ArrayList<ExcelResultDetailDTO>();
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            log.debug("共有 " + workbook.getNumberOfSheets() + " Sheets : ");
            int iMax = 0;
            //循环工作簿
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                //Date createTime = new Date();
                int rows = sheet.getPhysicalNumberOfRows();
                for (int row = 2; row < rows; row++) {
                    Row row_n = sheet.getRow(row);
                    if (row_n != null) {
                        //index++;
                        String index  = getValue(row_n.getCell(0)); //排序//忽略
                        String content  = getValue(row_n.getCell(1)); //内容
                        if (!StringUtils.isEmpty(content)){
                            RailLinkappWorkResponsibility responsibility  = new RailLinkappWorkResponsibility();
                            String id = UUID.randomUUID().toString().replaceAll("-","");
                            responsibility.setId(id);
                            responsibility.setWorkId(workId);
                            responsibility.setTenantId(tenantId);
                            responsibility.setContent(content);
                            responsibility.setSortIndex((iMax+1));
                            commonService.setCreateAndModifyInfo(responsibility);
                            baseMapper.insert(responsibility);
                            iMax =  responsibility.getSortIndex();
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private String getValue(Cell xSSFCell) {
        if (null == xSSFCell) {
            return "";
        }
        try {
            return String.valueOf(xSSFCell.getStringCellValue());
        } catch (Exception ex) {
        }
        return "";
    }
}
